import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

class HLStorage {
  /// SharedPreferences对象
  static SharedPreferences? _storage;

  /*
  * 初始化数据
  * */
  static initStorage() async {
    _storage ??= await SharedPreferences.getInstance();
  }

  /*
  * 存储
  * */
  static setStorage(String key, dynamic value) async {
    String type;
    // 监测value的类型 如果是Map和List,则转换成JSON，以字符串进行存储
    if (value is Map || value is List) {
      type = 'String';
      value = JsonEncoder().convert(value);
    } else {
      // 否则 获取value的类型的字符串形式
      type = value.runtimeType.toString();
    }
    switch (type) {
      case 'String':
        _storage?.setString(key, value);
        break;
      case 'int':
        _storage?.setInt(key, value);
        break;
      case 'double':
        _storage?.setDouble(key, value);
        break;
      case 'bool':
        _storage?.setBool(key, value);
        break;
    }
  }

  /*
  * 获取存储
  * */
  static T? getStorage<T>(String key) {
    if (!hasKey(key)) {
      return null;
    }
    Object? value = _storage?.get(key);
    if (value == null) {
      return null;
    }

    String type = value.runtimeType.toString();

    if (type == "int" || type == "double" || type == "bool") {
      return value as T;
    }

    try {
      // 如果value是一个json的字符串 则不会报错 返回true
      return JsonDecoder().convert(value as String);
    } catch (e) {
      return _storage?.get(key) as T;
    }
  }

  /*
  * 是否包含某个key
  * */
  static bool hasKey(String key) {
    return (_storage == null) ? false : _storage!.containsKey(key);
  }

  /*
  * 删除
  * */
  static Future<bool> remove(String key) async {
    if (await hasKey(key)) {
      await _storage?.remove(key);
      return true;
    } else {
      return false;
    }
  }

  /*
  * 清空存储
  * */
  static void clear() async {
    _storage?.clear();
  }

  /*
  * 获取所有的key 类型为Set<String>,
  * */
  Future<Set<String>> getKeys() async {
    return _storage!.getKeys();
  }
}
